package com.cuteboy.admin.controller;

import com.cuteboy.admin.service.SysPermissionService;
import com.cuteboy.admin.service.SysRoleService;
import com.cuteboy.admin.service.SysUserRoleService;
import com.cuteboy.admin.service.SysUserService;
import com.cuteboy.entity.SysRole;
import com.cuteboy.entity.SysUser;
import com.cuteboy.entity.SysUserRole;
import com.cuteboy.util.Constants;
import com.cuteboy.util.ValidateUtils;
import com.cuteboy.vo.Page;
import com.cuteboy.vo.ResponseVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysPermissionService sysPermissionService;

    /**
     * 定位到后台用户单页面
     * @return
     */
    @RequiresPermissions("admin:user")
    @RequestMapping("tousermanage")
    public String tousermanage(){
        return "page/user";
    }


    @RequiresPermissions(value = {"admin:user:list"})
    @ResponseBody
    @RequestMapping("/list")
    public ResponseVO page(Page page){
        List<SysUser> sysUsers = sysUserService.list(page.getPage(), page.getLimit());
        Integer count = sysUserService.countAll();
        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS, count, sysUsers);
    }

    @RequiresPermissions(value = {"admin:user:delete"})
    @ResponseBody
    @RequestMapping("/delete")
    public ResponseVO delete(@RequestParam String username){
        sysUserService.delete(username);
        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS);
    }

    @RequiresPermissions(value = {"admin:user:save"})
    @ResponseBody
    @RequestMapping("/save")
    public ResponseVO save(SysUser sysUser){
        sysUserService.save(sysUser);
        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS, sysUser);
    }

    @RequiresPermissions(value = {"admin:user:update"})
    @ResponseBody
    @RequestMapping("/update")
    public ResponseVO update(SysUser sysUser){
        sysUserService.update(sysUser);
        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS, sysUser);
    }


    // -------------------------------------------- 分隔用户管理页面接口，登录接口 --------------------------------------------------



    /**
     * 用户登录请求
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public Map<String,Object> login(@RequestParam String imageCode, SysUser user, BindingResult bindingResult, HttpSession session){
        Map<String,Object> map = new HashMap<String,Object>();
        if(ValidateUtils.isEmpty(imageCode)){
            map.put("success", false);
            map.put("errorInfo", "请输入验证码！");
            return map;
        }
        if(!session.getAttribute("checkcode").equals(imageCode)){
            map.put("success", false);
            map.put("errorInfo", "验证码输入错误！");
            return map;
        }
        if(bindingResult.hasErrors()){
            map.put("success", false);
            map.put("errorInfo", bindingResult.getFieldError().getDefaultMessage());
            return map;
        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try{
            subject.login(token); // 登录认证
            String username = (String) SecurityUtils.getSubject().getPrincipal();
            //Tuser currentUser=tuserService.findByUserName(userName);
            Example sysUserExample = new Example(SysUser.class);
            sysUserExample.or().andEqualTo("username",username);
            SysUser currentUser = sysUserService.selectByExample(sysUserExample).get(0);
            session.setAttribute("currentUser", currentUser);
            //List<Trole> roleList=troleService.findByUserId(currentUser.getId());
            List<SysRole> roleList = sysRoleService.selectRolesByUsername(currentUser.getUsername());
            map.put("roleList", roleList);
            map.put("roleSize", roleList.size());
            map.put("success", true);
            //logService.save(new Log(Log.LOGIN_ACTION,"用户登录")); // 写入日志
            return map;
        }catch(Exception e){
            e.printStackTrace();
            map.put("success", false);
            map.put("errorInfo", "用户名或者密码错误！");
            return map;
        }
    }

    /**
     * 保存角色信息
     * @param roleId
     * @param session
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PostMapping("/saveRole")
    public Map<String,Object> saveRole(Integer roleId,HttpSession session)throws Exception{
        Map<String,Object> map=new HashMap<String,Object>();
        SysRole currentRole = sysRoleService.selectByPrimaryKey(roleId);
        session.setAttribute("currentRole", currentRole); // 保存当前角色信息

        sysPermissionService.putTmenuOneClassListIntoSession(session);

        map.put("success", true);
        return map;
    }


    /**
     * 安全退出
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/logout")
    public String logout() throws Exception {
//		logService.save(new Log(Log.LOGOUT_ACTION,"用户注销"));
        SecurityUtils.getSubject().logout();
        return "redirect:/tologin";
    }

}
